
//
// Copyright 2009 Arne Halvorsen (arne.halvorsen@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// Project page: http://code.google.com/p/mf4j/

//
// 091125a- aha42 - Created.
// 091125b- aha42 - getProperties(CommandLineParser).
//

package org.aha.mf4j.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * <p>
 *   Utility methods of use when working with
 *   {@link Properties}.
 * </p>
 * @author Arne Halvorsen (aha42)
 */
public final class PropertiesUtil 
{
  private PropertiesUtil(){} // Utility pattern dictates private constructor.
  
  /**
   * <p>
   *   Gets either 
   *   {@link System#getProperties() system properties} or the properties loaded
   *   from file which path has been given by the {@code -properties <path>} 
   *   command line option.
   * </p>
   * @param clp Parsed command line.
   * @return {@link Properties}.
   * @throws IOException If fails to load from file.
   */
  public static Properties getProperties(CommandLineParser clp) 
    throws IOException
  {
    if (clp==null)
    {
      throw new NullPointerException("clp");
    }
    
    File f=clp.fileValue("-properties");
    if (f==null)
    {
      return System.getProperties();
    }

    Properties retVal=new Properties();
    FileInputStream fis=null;
    try
    {
      fis=new FileInputStream(f);
      retVal.load(fis);
      return retVal;
    }
    finally
    {
      if (fis!=null) try { fis.close(); } catch (IOException _){}  
    }
  }
  
  /**
   * <p>
   *   Gets mandatory property.
   * </p>
   * @param name  Property name.
   * @param props {@link Properties}.
   * @return Value.
   * @throws IllegalArgumentException If not found.
   */
  public static String getMandatoryProperty(String name, Properties props)
  {
    if (name==null)
    {
      throw new NullPointerException("name");
    }
    if (props==null)
    {
      throw new NullPointerException("props");
    }
    
    String val=props.getProperty(name);
    if (val==null)
    {
      throw new IllegalArgumentException("missing property : "+name);
    }
    return val;
  }
  
}
